﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomerService
{
    public partial class AddDetailItem : System.Web.UI.Page
    {
        private SalesManagerEntities _sme;

        protected void Page_Load(object sender, EventArgs e)
        {
            _sme = (SalesManagerEntities)Session["sme"];
            if (!IsPostBack && Request.QueryString["OrderID"] != string.Empty && Request.QueryString["OrderID"] != null)
            {
                tblOrderHeader oh = _sme.tblOrderHeader.Find(new object[] {int.Parse(Request.QueryString["OrderID"])});

                ListView1.DataSource = (from c in _sme.tblProduct where c.ProductGroup.OwnerID == oh.OwnerID && c.SalableItem == true orderby c.ItemCode select c).ToArray();
                ListView1.DataBind();
            }
        }

        protected void btnSelect_Click(object sender, CommandEventArgs e)
        {
            int key = int.Parse(e.CommandArgument.ToString());

            tblOrderHeader oh = _sme.tblOrderHeader.Find(new object[] {int.Parse(Request.QueryString["OrderID"])});

            tblOrderDetail newDetail = new tblOrderDetail();
            newDetail.OrderHeader = oh;
            newDetail.ImportDate = DateTime.Today;
            newDetail.Product = _sme.tblProduct.Find(new object[] {key});
            newDetail.Qty = 1;
            newDetail.UnitPrice = 1;
            newDetail.Discount = 0;
            _sme.tblOrderDetail.Add(newDetail);
            _sme.SaveChanges();
            Session["sme"] = _sme;

            //_sme.Refresh(System.Data.Objects.RefreshMode.StoreWins, 
            //    oh.OrderDetails);

            // Trigger the OrderDetail panel to refresh.            
            if (!Page.ClientScript.IsStartupScriptRegistered("PostBack"))
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PostBack",
                    "<script  language='javascript' type='text/javascript'>" +
                    "opener.__doPostBack('" + Request.QueryString["PanelID"] + "', 'UpdateDetails'); window.close('fred');" +
                    "</script>"
                    );
        }

        protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
        {
        }
    }
}
